package com.lfsenior.jms;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by dlupan on 2018/10/31
 */
public class MessageSender {
    /**
     * 发送消息
     * @param session
     * @param producer
     */
    public static void sendMessage(Session session, MessageProducer producer) throws Exception{
        for(int i=0;i<5;i++){
            String message = "发送消息第" + (i + 1) + "条";
            TextMessage textMessage = session.createTextMessage(message);
            System.out.println(message);
            producer.send(textMessage);

        }
    }

    public static void run() throws Exception{
        // 创建连接工厂
        ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        // 创建连接
        Connection connection = factory.createConnection();
        // 启动连接
        connection.start();
        // 创建session会话
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        // 创建消息镦列
        Destination queue = session.createQueue("JMS-QUEUE");
        // 创建消息生产者
        MessageProducer producer = session.createProducer(queue);
        // 启动持久化模式
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        // 发送消息
        sendMessage(session,producer);
        //提交会话
        session.commit();
        //关闭会话
        session.close();
        connection.close();
    }

    public static void main(String[] args) throws Exception{
        MessageSender.run();
    }
}
